package com.wanlian.context.Notice;

import com.wanlian.entity.NoticeMsg;
import com.wanlian.util.DateUtil;
import com.wanlian.vo.NoticeMsgResultVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class NoticeManager {
    private static long timespan = 1000;

    private static Map<Integer, Long> preSendRecords = new HashMap<>();

    public static Map<Integer, NoticeCache> needCaches = new HashMap<>();

    public static synchronized void add(Integer userId, NoticeMsgResultVo vo) {

        if (needCaches.containsKey(userId)) {
            needCaches.get(userId).getNoticeMsgResultVos().add(vo);
        } else {
            NoticeCache noticeCache = new NoticeCache();
            noticeCache.setUserId(userId);
            List<NoticeMsgResultVo> noticeMsgResultVos = new ArrayList<>();
            noticeMsgResultVos.add(vo);
            noticeCache.setNoticeMsgResultVos(noticeMsgResultVos);
            needCaches.put(userId, noticeCache);
        }
    }

    public static synchronized NoticeMsg getNoticeMsg(Integer userId, NoticeMsg noticeMsg) {

        return null;
    }

    // 调价到历史记录中
    public static synchronized void addRecords(Integer userId) {
        preSendRecords.put(userId, DateUtil.currentTimestamp().getTime());
    }

    // 获取上次发送的时间
    public static synchronized boolean canSend(Integer userId) {
        if (preSendRecords.containsKey(userId)) {
            Long presendTime = preSendRecords.get(userId);
            long tspan = DateUtil.currentTimestamp().getTime() - presendTime.longValue();
            if (tspan >= timespan) {
                return true;
            }
            return false;
        } else {
            return true;
        }
    }

    // 获取上次发送的时间
    public static synchronized void tidyMsg() {
        if (needCaches.size() > 0) {
            for (Integer userId : needCaches.keySet()) {
                if (canSend(userId)) {
                    NoticeCache noticeCache = needCaches.get(userId);
                    noticeCache.tidyMsgs();
                    if (noticeCache.getNoticeMsgResultVos().size() > 0) {
                        NoticeMsgResultVo vo = noticeCache.getNoticeMsgResultVos().get(0);
                        noticeCache.getNoticeMsgResultVos().remove(0);
                        {
                            NoticeMsgContext.add(vo);
                        }
                    }
                }
            }
        }
    }
}
